package inet.app.vod.util;

import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;

public class ListViewUtil {
	/*
	 * This is method to set height of ListView. it usually use when ListView inside ScrollView.
	 * After method used, ListView can't scroll.
	 */
	public static void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}
		
		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();

		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
		listView.requestLayout();
	}
	/*
	 * This is method to set height of GridView. it usually use when GridView inside ScrollView
	 */
	public static void setGridViewHeightBasedOnChildren(GridView gridView, int itemPerRow) {
		
		ListAdapter listAdapter = gridView.getAdapter();
		
		if (listAdapter == null) {
			// pre-condition
			return;
		}
		
		int totalHeight = 0;
		int rowNumber = listAdapter.getCount() / itemPerRow;
		
		if(listAdapter.getCount() > 0){
			View listItem = listAdapter.getView(0, null, gridView);
			listItem.measure(0, 0);
			totalHeight = (rowNumber + 1) * listItem.getMeasuredHeight();
		}
		
		ViewGroup.LayoutParams params = gridView.getLayoutParams();
		
		params.height = totalHeight + (5) + 5 * ((listAdapter.getCount() - 1) / itemPerRow);
		
		gridView.setLayoutParams(params);
		gridView.requestLayout();
	}

}